package com.itydl.a05.view;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.itydl.a05.R;

/**
 * @author ydl
 * @version 仿美团下拉刷新效果实现
 */

public class RefreshListView extends ListView {

    private static final String TAG = "ITYDL";

    private Context mContext;
    private OnRefreshListener mOnRefreshListener;
    private View mHeaderView;
    private int mHeaderHeight;//头布局的高度
    private RefreshFirstStepView mFirstStepView;//下拉刷新的View
    private RefreshSecondStepView mSecondStepView;//释放刷新的View
    private RefreshThirdStepView mThirdStepView;//正在刷新的View
    private TextView mTvDes;//刷新状态的描述信息
    private int mImageHeight;//三个View的高度都是一样的，所以选择一个拿到高度即可。他作为手势滑动的最大距离
    private int mTouchEventMaxLen;//手势滑动的最大距离
    private AnimationDrawable secondAnim;//第二个View即释放刷新状态的图片
    private AnimationDrawable mThreeAnim;//第三个View即正在刷新状态的图片
    private float downY = -1;

    private static final int PULL_TO_REFRESH = 1;//下拉刷新状态
    private static final int RELEASE_TO_REFRESH = 2;//释放刷新状态
    private static final int REFRESHING = 3;//正在刷新状态
    private int currentSatae = PULL_TO_REFRESH;//当前状态，默认为下拉刷新状态

    public void setOnRefreshListener(OnRefreshListener onRefreshListener){
        mOnRefreshListener = onRefreshListener;
    }


    /**
     * 下拉刷新监听器
     */
    public interface OnRefreshListener{
        /**
         * 正在刷新
         */
        void onRefreshing();
    }

    public RefreshListView(Context context) {
        this(context,null);
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initHearder();
        initAnimation();
    }

    /**
     * 对动画的初始化
     */
    private void initAnimation() {
        mSecondStepView.setBackgroundResource(R.drawable.pull_to_refresh_second_anim);
        secondAnim = (AnimationDrawable) mSecondStepView.getBackground();

        mThirdStepView.setBackgroundResource(R.drawable.pull_to_refresh_third_anim);
        mThreeAnim = (AnimationDrawable) mThirdStepView.getBackground();
    }

    /**
     * 初始化头
     */
    private void initHearder() {
        mHeaderView = LayoutInflater.from(mContext).inflate(R.layout.layout_header,null);
        mFirstStepView = (RefreshFirstStepView) mHeaderView.findViewById(R.id.first_view);
        mSecondStepView = (RefreshSecondStepView) mHeaderView.findViewById(R.id.second_view);
        mThirdStepView = (RefreshThirdStepView) mHeaderView.findViewById(R.id.third_view);
        mTvDes = (TextView) mHeaderView.findViewById(R.id.tv_pull_to_refresh);

        mHeaderView.measure(0,0);

        mHeaderHeight = mHeaderView.getMeasuredHeight();
        //        Log.e(TAG,"头高度为：--->"+mHeaderHeight);

        mHeaderView.setPadding(0,-mHeaderHeight,0,0);

        addHeaderView(mHeaderView);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mImageHeight = mFirstStepView.getMeasuredHeight();
        mTouchEventMaxLen = mImageHeight;
//        Log.e(TAG,"view1高度：--->"+mFirstStepView.getMeasuredHeight()+"~~view2高度：--->"+mSecondStepView.getMeasuredHeight()+"~~view3高度：--->"+mThirdStepView.getMeasuredHeight());
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downY = ev.getY();
                    break;
                case MotionEvent.ACTION_MOVE:

                    if(downY == -1){
                        downY = ev.getY();
                    }

                    float moveY = ev.getY();
                    //如果当前处于下拉刷新状态，不去走下面的代码
                    if(currentSatae == REFRESHING){
                        return false;//如果当前处于正在刷新状态，取消后续的所有事件包括上滑和下滑
                    }

                    float instance = (moveY - downY)/3;
                    if(getFirstVisiblePosition() == 0 && instance >= 0){//0item且下拉
                        int topPadding = (int) (-mHeaderHeight + instance +0.5f);//计算padding值
                        if(topPadding > -mHeaderHeight){//只有padding值大于-mHeaderHeight的时候才去自己处理事件
                            if(topPadding < 0 && currentSatae != PULL_TO_REFRESH){
//                                Log.e(TAG,"下拉刷新状态");
                                currentSatae = PULL_TO_REFRESH;
                            }else if(topPadding >= 0 && currentSatae != RELEASE_TO_REFRESH){
//                                Log.e(TAG,"释放刷新状态");
                                currentSatae = RELEASE_TO_REFRESH;
                            }
                        }
                        mHeaderView.setPadding(0,topPadding,0,0);
                        refreshState(instance);
                        return true;//自己处理事件
                    }

                    break;
                case MotionEvent.ACTION_UP:
                    downY = -1;
                    if(currentSatae == RELEASE_TO_REFRESH){
                        //当前状态是释放刷新，松手后是正在刷新状态
                        currentSatae = REFRESHING;
                        //还原Padding,使用Scroll平滑移动过去
                        mHeaderView.setPadding(0,0,0,0);
                        refreshState(mHeaderHeight);
                        if(mOnRefreshListener != null){
                            mOnRefreshListener.onRefreshing();
                        }
                    }else if(currentSatae == PULL_TO_REFRESH){
                        //使用Scroll平滑移动过去
                        mHeaderView.setPadding(0,-mHeaderHeight,0,0);
                    }
                    break;

                default:
                    break;
         }

        return super.onTouchEvent(ev);//ListView的事件保留
    }

    /**
     * 刷新当前的状态
     * 根据标记为处理控件的样式数据
     * @param instance
     */
    private void refreshState(float instance) {

        //计算比例
        float moveY = Math.abs(instance);

        float percent = moveY / mHeaderHeight;
        if(percent >= 1.0f){
            percent = 1.0f;
        }
        Log.e(TAG,"百分比-->"+percent);

        switch (currentSatae) {
            case PULL_TO_REFRESH:
                mFirstStepView.setVisibility(VISIBLE);
                mSecondStepView.setVisibility(GONE);
                mThirdStepView.setVisibility(GONE);
                mTvDes.setText("下拉刷新");
                //执行动画
                mFirstStepView.setProgress(percent);
                mFirstStepView.postInvalidate();
                break;
            case RELEASE_TO_REFRESH:
                mFirstStepView.setVisibility(GONE);
                mSecondStepView.setVisibility(VISIBLE);
                mThirdStepView.setVisibility(GONE);
                mTvDes.setText("释放刷新");
                secondAnim.start();
                break;
            case REFRESHING:
                mFirstStepView.setVisibility(GONE);
                mSecondStepView.setVisibility(GONE);
                mThirdStepView.setVisibility(VISIBLE);
                mTvDes.setText("正在刷新");
                mThreeAnim.start();
                break;

            default:
                break;
            }
    }

    /**
     * 在下拉刷新完成之后记得调用一下刷新完成的方法
     */
    public void setOnRefreshComplete() {
        //对各控件做初始化处理
        secondAnim.stop();
        mThreeAnim.stop();
        mFirstStepView.setVisibility(VISIBLE);
        mSecondStepView.setVisibility(GONE);
        mThirdStepView.setVisibility(GONE);
        mTvDes.setText("下拉刷新");
        mHeaderView.setPadding(0,-mHeaderHeight,0,0);
        currentSatae = PULL_TO_REFRESH;
    }
}
